<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/3/27
 * Time: 9:34
 */
namespace api\modules\shop\controllers;

//use yii\web\Controller;
use common\models\Active;
use common\models\ActiveAttr;
use common\models\ActivityAttr;
use common\models\GoodsAttr;
use common\models\Order;
use common\models\Shop;
use common\service\CommonService;
use common\service\ConstantService;
use common\service\GlobalUrlService;
use common\service\ActiveService;
use common\service\GoodsService;
use common\models\Goods;
use common\models\GoogsAttr;
use common\service\WechatService;

class ActiveController extends ShopBaseController{

    //数据中心
    public function actionIndex(){

        $start_time = strtotime(date('Y-m-d ') . '00:00:00');
        $end_time = strtotime(date('Y-m-d ') . '23:59:59');
        //需要统计的数据
        //1 日,总订单数
        $order_query = Order::find();
        $max_time = ['>=', 'created_time', $start_time];
        $min_time = ['<=', 'created_time', $end_time];
        $pay_status = ['=', 'pay_status', 1];
        $shop_ids = ['=', 'shop_id', $this->shop['id']];
        $noeq = ['!=', 'order_status', 6];
        $day_order = $order_query->select('count(id) as day_order_count')
            ->andWhere($max_time)
            ->andWhere($min_time)
            ->andWhere($pay_status)
            ->andWhere($shop_ids)
            ->andWhere(['>=', 'order_status', 1])
            ->asArray()
            ->one();
        $count_order = Order::find()->select('count(id) as order_count')
            ->andWhere($pay_status)
            ->andWhere($shop_ids)
            ->andWhere(['>=', 'order_status', 1])
            ->asArray()
            ->one();

        //2. 日,总商品销量 算法: 已完成
        $count_goods = Order::find()->select('sum(goods_num) as goods_count')
            ->andWhere($pay_status)
            ->andWhere($shop_ids)
            ->andWhere($noeq)
            ->asArray()
            ->one();
        //3 日,总销售金额 算法:已完成
        //日销售金额
        $day_money_ywc = $order_query->select('sum(order_money) as day_money_count')
            ->andWhere($max_time)
            ->andWhere($min_time)
            ->andWhere($pay_status)
            ->andWhere($noeq)
            ->andWhere($shop_ids)
            ->asArray()
            ->one();
        //总销售金额
        $count_money_ywc = Order::find()->select('sum(order_money) as money_count')
            ->andWhere($pay_status)
            ->andWhere($noeq)
            ->andWhere($shop_ids)
            ->asArray()
            ->one();
        //4. 退款订单
        $order_status_4 = Order::find()->select('count(id) as count_order')
            ->where(['shop_id'=>$this->shop['id'],'order_status'=>4,'is_delete'=>0])->asArray()->one();
        //5. 待发货订单
        $order_status_1 = Order::find()->select('count(id) as count_order')
            ->where(['shop_id'=>$this->shop['id'],'order_status'=>1])->asArray()->one();
        //店铺logo
        $shop=Shop::find()->where(['id'=>$this->shop['id']])->one();
        $shop_logo=GlobalUrlService::buildCdnUrl($shop['shop_logo']);

        //店铺名称
        $shop_name=$shop['shop_name'];

        $data_center = [
            'day_count' => $day_order['day_order_count'],
            'order_countAll' => $count_order['order_count'],
            'count_goods' => $count_goods['goods_count'],
            'money_totle' =>substr(sprintf("%.3f", $day_money_ywc['day_money_count']),0,-1),//round($day_money_ywc['day_money_count'],2),
            'money_totleAll' =>substr(sprintf("%.3f", $count_money_ywc['money_count']),0,-1),//round($count_money_ywc['money_count'],2),
            'tui_count' =>$order_status_4['count_order'],
            'dai_count' =>$order_status_1['count_order'],
            'shop_logo'=>$shop_logo,
            'shop_name'=>$shop_name
        ];

        return $this->renderJson([$data_center],'数据中心：tui_count退款中订单数，dai_count代发货订单数，day_count日订单数，money_totle日销售总金额,shop_logo店铺logo',ConstantService::$response_success);
    }
    /*
     * 商家活动列表
     * */
    public function actionActive(){
            $name=$this->post('name');
            $shop_id=$this->shop['id'];
            $ac_query = Active::find();
            $ac_query->andWhere(['is_del'=>0]);
            $ac_query->andWhere(['shop_id'=>$shop_id]);
            if(!empty($name)){
                $ac_query->andWhere(['like','active_name',$name]);
            }
            $p = intval( $this->post('page',1) );
            $p = ( $p > 0 )? $p : 1;
            $offset = ($p - 1) *  $this->page_size;
            $data_end1 = $ac_query->limit( $this->page_size)->orderBy('create_time desc')->offset($offset)->asArray()->all();
            foreach ($data_end1 as $value){
                if (intval($value['end_time'])<time()){
                    $attr_status = Active::find()->where(['id'=>$value['id']])->one();
                    $attr_status['status']=2;
                    $attr_status->save();
                }
            }
            $data_end = $ac_query->limit( $this->page_size)->offset($offset)->asArray()->all();
            return $this->renderJson([$data_end,$name],'',ConstantService::$response_success);
    }

    /*
     * 单个开始活动
     * */
    public function actionBegin(){
        if ($this->isPost()){
            $id = $this->post('id');
            $data = Active::find()->where(['id'=>$id])->one();
            $data['status']=1;
            $re = $data->save();
            if ($re){
                return $this->renderJson([],'激活成功',ConstantService::$response_success);
            }else{
                return $this->renderJson([],'激活失败',ConstantService::$response_fail);
            }
        }
    }

    /*
     * 开始全部活动
     * */
    public function actionBeginAll(){
       // if ($this->isPost()){
        $id = empty($this->shop['id'])?1:$this->shop['id'];
        $active_model = Active::find();
        $active_model->select('id');
        $active_model->andWhere(['>','end_time',time()]);
        $active_model->andWhere(['<=','begin_time',time()]);
        $active_model->andWhere(['shop_id'=>$id]);
        $active_model->asArray();
        $data = $active_model->all();
        $aid = [];
        foreach ($data as $v){
            $aid[] = $v['id'];
        }
        if(Active::updateAll(['status'=>1,'update_time'=>time()],['id'=>$aid])){
            return $this->renderJson([],'所有活动激活成功',ConstantService::$response_success);
        }else{
            return $this->renderJson([],'所有活动激活失败',ConstantService::$response_fail);
        }
       // }
    }

    /*
     * 暂定某一个活动
     */
    public function actionEnd(){
        if($this->isPost()){
            $id = $this->post('id');
            $data = Active::find()->where(['id'=>$id])->one();
            $data['status']=0;
            $re = $data->save();
            if ($re){
                return $this->renderJson([],'暂停成功',ConstantService::$response_success);
            }else{
                return $this->renderJson([],'暂停失败',ConstantService::$response_fail);
            }
        }
    }

    /*
     *   暂停所有活动
     * */
    public function actionEndAll(){
        //if($this->isPost()){
        $id = empty($this->shop['id'])?1:$this->shop['id'];
        $active_model = Active::find();
        $active_model->select('id');
        $active_model->andWhere(['>','end_time',time()]);
        $active_model->andWhere(['<=','begin_time',time()]);
        $active_model->andWhere(['shop_id'=>$id]);
        $active_model->asArray();
        $data = $active_model->all();
        $aid = [];
        foreach ($data as $v){
            $aid[] = $v['id'];
        }
        if(Active::updateAll(['status'=>0,'update_time'=>time()],['id'=>$aid])){
            return $this->renderJson([],'所有活动暂停成功',ConstantService::$response_success);
        }else{
            return $this->renderJson([],'所有活动暂停失败',ConstantService::$response_fail);
        }
       // }
    }

    /*
     * 查案活动详情（活动列表页面点击“查看/编辑”）
     * */
    public function actionSelect(){
        if ($this->isPost()){
            $activity_id = $this->post('id');
            $activity = Active::find()->where(['id'=>$activity_id])->one();
            $attr = ActiveService::GetAttrlist($activity_id);
            return $this->renderJson(['activity'=>$activity,'activity_attr'=>$attr],"查看成功",ConstantService::$response_success);
        }else{
            return $this->renderJson([],'请用正确的方式进入查看页面',ConstantService::$response_fail);
        }
    }

    /*
     * 加载活动修改页面
     * */
    public function actionUpdata(){
        $activity_id = $this->post('id');
        $activity = Active::find()->where(['id'=>$activity_id])->one();
        $activity_attr = ActiveService::GetAttrlist($activity_id);
        return $this->renderJson(['activity'=>$activity,'activity_attr'=>$activity_attr,'goods_id'=>$activity_id],"返回成功",ConstantService::$response_success);
    }
    /*
     * 活动修改接口
     * */
    public function actionUpdataindex(){
        $activity_id = $this->post('id');

        $avtivity_attr = json_decode($this->post("activity_attr"),true);

        if (empty($avtivity_attr)){
            return $this->renderJson([],'请选择活动商品规格',ConstantService::$response_fail);
        }
        //添加活动的时间有效性
        if (strtotime($this->post('begin_time'). ' 00:00:00') >= strtotime($this->post('end_time'). ' 23:59:59')){
            return $this->renderJson([],'结束的时间需大于开始时间',ConstantService::$response_fail);
        }
        //判断活动库存
        //前端传来的活动属性id
        $goods_attr_id = array_column($avtivity_attr,'goods_attr_id');
        $goods_attr_data = GoodsAttr::find()->select(['id','inventory'])->where(['in','id',$goods_attr_id])->asArray()->all();

        foreach ($avtivity_attr as $v){
            foreach ($goods_attr_data as $gd){
                if ($v['goods_attr_id'] == $gd['id']){
                    if (trim($gd['inventory']) <  trim($v['inventory'])){
                        return $this->renderJson([],'活动库存大于商品库存，请重新填写',ConstantService::$response_fail);
                    }
                }
            }
        }

        $activity = Active::find()->where(['id'=>$activity_id])->one();
        $activity->setAttributes([
            'active_name'=> $this->post('active_name') ,
            'active_num'=>$this->post('active_num') ,
            'begin_time'=>strtotime($this->post('begin_time'). ' 00:00:00') ,
            'end_time'=>strtotime($this->post('end_time'). ' 23:59:59') ,
            'status'=>0 ,
        ]);

        $save = $activity->save();

        if ($save){
            //获取前端传过来的属性值
            foreach ($avtivity_attr as $value) {
                    $activityAttr_one = ActiveAttr::find()->where(['id' => $value['id']])->one();
                    $activityAttr_one['original_price'] = $value['original_price'];
                    $activityAttr_one['one_price'] = $value['one_price'];
                    $activityAttr_one['collage_price'] = $value['collage_price'];
                    $activityAttr_one['inventory'] = $value['inventory'];
                    $activityAttr_one->save();
            }
            return $this->renderJson([],"修改成功",ConstantService::$response_success);

        }
        return $this->renderJson([],'活动主表修改失败',ConstantService::$response_fail);
    }
    /*
     * 删除活动
     * */
    public function actionDel(){
        if ($this->isPost()){
            $id = $this->post('id');
            $re = Active::findOne($id);
            $re->is_del = 1;
            if ($re->save()){
                ActiveService::DelActive($id);
                return $this->renderJson([],'删除成功',ConstantService::$response_success);
            }else{
                return $this->renderJson([],'删除失败',ConstantService::$response_fail);
            }
        }

    }



    /*
     * 加载添加活动提交接口
     * */
    public function actionAdd(){
        $activity= new Active();
        if ($this->isPost()){
            $goodsattrdatas = json_decode($this->post('avtivity_attr'),true);
            if (empty($goodsattrdatas)){
                return $this->renderJson([],'请选择活动商品规格',ConstantService::$response_fail);
            }
            if (strtotime($this->post('begin_time'). ' 00:00:00') >= strtotime($this->post('end_time'). ' 23:59:59')){
                return $this->renderJson([],'结束的时间需大于开始时间',ConstantService::$response_fail);
            }
            //前端传来的商品属性
            $goods_attr_id = array_column($goodsattrdatas,'goods_attre_id');
            $goods_attr_data = GoodsAttr::find()->select(['id','inventory'])->where(['in','id',$goods_attr_id])->asArray()->all();
            $newgoodsattr = [];
            foreach ($goods_attr_data as $val){
                $newgoodsattr[$val['id']] = $val;
            }
            $modify_inventory = []; //需要修改的库存和id
            $errors = '';


            //判断库存
            foreach ($goodsattrdatas as $attr){
                if(isset($newgoodsattr[$attr['goods_attre_id']] ) && !empty($newgoodsattr[$attr['goods_attre_id']])){
                    if($newgoodsattr[$attr['goods_attre_id']]['inventory'] < $attr['inventory']){
                        $errors .= '拼团价为'.$attr['collage_price'] .'的商品库存小于活动库存,';
                        continue;
                    }else{
                        $arr['id'] = $attr['goods_attre_id'];
                        $arr['inventory'] = $newgoodsattr[$attr['goods_attre_id']]['inventory'] - $attr['inventory'];

                        array_push($modify_inventory,$arr);
                    }
                }
            }

            if(!empty($errors)){
                return $this->renderJson([],$errors,ConstantService::$response_fail);
            }

            //添加活动表
            $activity->setAttributes([
                'shop_id'=> empty($this->shop['id'])?1:$this->shop['id'],
                'goods_id'=> $this->post('goods_id') ,
                'active_name'=> $this->post('active_name') ,
                'active_num'=> $this->post('active_num') ,
                'begin_time'=> strtotime($this->post('begin_time'). ' 00:00:00') ,
                'end_time'=> strtotime($this->post('end_time'). ' 23:59:59') ,
                'status'=> 0,
                'qrcode' => '',
                'is_del'=> 0,
                'create_time'=> time(),
                'update_time'=> time(),
            ]);

            $save_activity = $activity->save();
            if($save_activity){
                $active_id = \Yii::$app->db->getLastInsertID();
                foreach ($goodsattrdatas as &$attr){
                    $attr['active_id'] = $active_id;
                    $attr['sales_volume'] = 0;
                    $attr['is_del'] = 0;
                    $attr['create_time'] = time();
                    $attr['update_time'] = time();
                }
                //保存属性值
                $re = ActiveAttr::getDb()->createCommand()->batchInsert('active_attr',
                    ['goods_attre_id','attr_img','one_price','original_price','collage_price','inventory','attribute_value_id','active_id','sales_volume','is_del','create_time','update_time'],
                    $goodsattrdatas)->execute();
                if($re){
                    //减商品库存
                    $this->_modifyInventory($modify_inventory);
                    return $this->renderJson([],'活动添加成功',ConstantService::$response_success);
                }

                return $this->renderJson([],'保存活动属性失败',ConstantService::$response_fail);
            }else{
                return $this->renderJson([],'活动主表添加失败',ConstantService::$response_fail);
            }
        }
    }
    /**
     * 修改库存
     * @param $data
     * @return bool
     */
    private function _modifyInventory($data){
        if(empty($data)){
            return false;
        }

        foreach ($data as $val){
            $goods = GoodsAttr::findOne(['id'=>$val['id']]);
            $goods->inventory = $val['inventory'];
            $goods->save();
        }

        return true;
    }

    /**
     * 商品搜索
     */
    public function actionAddSelect(){

        $goods_name = $this->get('goods_name');
        $query = Goods::find();
        $query->andWhere(['is_del'=>0]);
        if(!empty($goods_name)){
            $query->andWhere(['like','goods_name',$goods_name]);
        }

        $p = intval( $this->get('p',1) );
        $p = ( $p > 0 )? $p : 1;

        $offset = ($p - 1) * $this->page_size;

        $lists = $query
            ->select(['id','goods_name'])
            ->orderBy(['created_at' => SORT_DESC, 'id' => SORT_ASC])
            ->offset( $offset )
            ->limit( $this->page_size )
            ->asArray()
            ->all();
        $data['lists'] = $lists;
        $pages = CommonService::ipagination( [
            'total_count' => $query->count(),//总条数
            'page_size' => $this->page_size,
            'page' => $p,
            'display' => 10
        ]);
        $data['count'] = $pages;
        return $this->renderJson($data,'获取成功',ConstantService::$response_success);
    }
    /**
     * 获取商品SKU
     */
    public function actionGetsku(){
        $goods_id = $this->post('id');
        $GoodsSer = new GoodsService();
        $skuData = GoodsService::GetAttrlist($goods_id,1);
        $cdn = GlobalUrlService::buildCdnUrl('');
        if ($skuData){
            return $this->renderJson(['goods_attr'=>$skuData,'cdn'=>$cdn],"获取成功",ConstantService::$response_success);
        }else{
            return $this->renderJson([],'获取失败',ConstantService::$response_fail);
        }
    }

    //活动二维码
    public function actionQrcode(){
            $aid = $this->post('id');
            $active = Active::find()->where(['id'=>$aid])->one();
            if (empty($active['qrcode'])){
                $qrcode = WechatService::getWechatQrcode('?id='.$aid,"pages/detail/detail");
                if($qrcode===false){
                    return $this->renderJson([],'获取失败',ConstantService::$response_fail);
                }else{
                    $active["qrcode"] = $qrcode;
                    $active->save();
                    $cdnUrl = GlobalUrlService::buildCdnUrl($qrcode);
                    return $this->renderJson(['cdnUrl'=>$cdnUrl],"获取成功",ConstantService::$response_success);
                }
            }else{
                $path = $active["qrcode"];
                $cdnUrl = GlobalUrlService::buildCdnUrl("$path");
                return $this->renderJson(['cdnUrl'=>$cdnUrl],"获取成功",ConstantService::$response_success);
            }
    }

}